package com.bc.trade.service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import com.bc.common.CommonEnum.OrderStatus;
import com.bc.common.CommonEnum.Resp;
import com.bc.common.PayType;
import com.bc.common.message.AccountBalanceChangeResp;
import com.bc.trade.channel.ChannelFactory;
import com.bc.trade.channel.IChannel;
import com.bc.trade.message.QueryOrderResp;
import com.bc.trade.model.Channel;
import com.bc.trade.model.TradeOrder;
import com.bc.trade.noitfy.NotifyThread;
import com.fs.common.util.FSLog;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;

public class QueryTask implements Runnable {

	private static VirtualAccountService accountService = new VirtualAccountService();
	
	@Override
	public void run() {
		FSLog.task.info("微信国际定时查询订单状态任务开始执行……");
		// 查询30秒前2小时内状态未知的订单号
		String timeBegin = LocalDateTime.now().minusHours(2).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		String timeEnd = LocalDateTime.now().minusSeconds(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		String sql = "select orderNo from trade_order where createTime between ? and ? and orderStatus IN(?, ?, ?)";
		List<String> orderNos = Db.query(sql, timeBegin, timeEnd, OrderStatus.InProcess.getValue(), OrderStatus.Unknow.getValue(), OrderStatus.Create.getValue());
		FSLog.task.info("定时需要查询状态的订单数量["+orderNos.size()+"]，条件：时间["+timeBegin+"]至["+timeEnd+"]且订单状态属于["+OrderStatus.InProcess.getName()+";"+OrderStatus.Unknow.getName()+";"+OrderStatus.Create.getName()+"]");		
		for (String orderNo : orderNos) {
			// 逐个订单号使用事务处理
			Db.tx(()->{
				// 行锁取出订单
				TradeOrder order = TradeOrder.dao.selectByOrderNoForUpdate(orderNo);
				if (order == null) {
					FSLog.task.info("定时查询订单号不存在orderNo=[" + orderNo + "]");
					return true;
				}
				FSLog.task.info("定时查询状态订号：" + order.getOrderNo());
				// 订单状态检测
				if(OrderStatus.Create.getValue().equals(order.getOrderStatus())
						||OrderStatus.Unknow.getValue().equals(order.getOrderStatus())
						|| OrderStatus.InProcess.getValue().equals(order.getOrderStatus()))
				{
					try {
						//  调用渠道查询
						IChannel channel = ChannelFactory.get(order.getChannelCode());
						QueryOrderResp rsp = channel.query(order);
						if (order.getPayType().equals(PayType.DF_PERSONAL) || order.getPayType().equals(PayType.DF_COMPANY)) {
							rsp = channel.dfQuery(order);
						} else {
							rsp = channel.query(order);
						}
						// 渠道返回状态明确时更新数据库
						if (rsp.getOriginalRespCode().equals(Resp.Fail.getCode()) 
								|| rsp.getOriginalRespCode().equals(Resp.Success.getCode())) {
							order.setRespCode(rsp.getOriginalRespCode());
							order.setRespMsg(rsp.getOriginalRespMsg());
							if (rsp.getOriginalRespCode().equals(Resp.Success.getCode())) {
								order.setOrderStatus(OrderStatus.Success.getValue());
								order.setPayTime(rsp.getPayTime());
							} else {
								order.setOrderStatus(OrderStatus.Fail.getValue());
							}
							if (StrKit.notBlank(order.getPayTime())) {
								order.setSettleDate(Channel.findSettleDate(order));
							}
							AccountBalanceChangeResp accountResp = accountService.processVirtualAccount(order);
							if(accountResp != null) {
								order.setBalance(Long.valueOf(accountResp.getBalance()));
							}
							order.update();
							//通知商户
							NotifyThread.getInstance().addNotifyOrder(order);
						}
						return true;
					} catch (Exception e) {
						FSLog.task.error("定时查询订单状态异常", e);
						return false;
					}
				} else {
					// 状态明确的订单不处理(或已经收到异步通知了)
					return true;
				}
			});
		}
		FSLog.task.info("定时查询订单状态任务执行完毕");
	}
	

}
